package com.wzq.tcpTio.tempcontroller;

import com.wzq.tcpTio.config.HelloClientAioHandler;
import com.wzq.tcpTio.config.HelloPacket;
import com.wzq.tcpTio.config.HelloServerAioHandler;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientTioConfig;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.core.Node;
import org.tio.core.Tio;
import org.tio.server.ServerTioConfig;
import org.tio.server.TioServer;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/demo")
@Validated
public class DemoController {

    private ClientChannelContext clientChannelContext;
    private ServerTioConfig serverTioConfig;

    /**
     */
    @PostMapping("/sendToServer")
    public String sendToServer(String msg) throws UnsupportedEncodingException {
        byte[] bytes = msg.getBytes(HelloPacket.CHARSET);

        HelloPacket packet = new HelloPacket();
        packet.setBody(bytes);
        if (clientChannelContext == null) {
            return "客户端未启动";
        }
        Tio.send(clientChannelContext, packet);

        return "success";
    }

    /**
     */
    @PostMapping("/sendToClient")
    public String sendToClient(String msg) throws UnsupportedEncodingException {
        byte[] bytes = msg.getBytes(HelloPacket.CHARSET);

        HelloPacket packet = new HelloPacket();
        packet.setBody(bytes);
        if (serverTioConfig == null) {
            return "服务端未启动";
        }
        Tio.sendToAll(serverTioConfig, packet);

        return "success";
    }

    /**
     */
    @PostMapping("/clientStarter")
    public void clientStarter() throws Exception {
        ClientTioConfig clientTioConfig = new ClientTioConfig(new HelloClientAioHandler(), null, new ReconnConf(5000L));
        clientTioConfig.setHeartbeatTimeout(5000);
        TioClient tioClient = new TioClient(clientTioConfig);
        clientChannelContext = tioClient.connect(new Node("127.0.0.1", 8055));
        HelloPacket packet = new HelloPacket();
        packet.setBody("hello world".getBytes(HelloPacket.CHARSET));
        Tio.send(clientChannelContext, packet);
    }

    /**
     * 启动服务
     *
     * @throws IOException
     */
    @PostMapping("/serverStarter")
    public void serverStarter() throws IOException {
        //ServerAioListener aioListener;
        serverTioConfig = new ServerTioConfig("hello-tio-server", new HelloServerAioHandler(), null);
        //设置心跳周期
//        serverTioConfig.setHeartbeatTimeout(5000);
        TioServer tioServer = new TioServer(serverTioConfig);
        //启动服务器
        tioServer.start(null, 8055);
    }

}
